<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Order;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Layout\Column;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Http\Controllers\AdminController;
use App\Admin\Metrics\Orders;
use App\Admin\Actions\Grid\ForbiddenOp;

class OrderController extends AdminController
{
    public function index(Content $content)
    {
        return $content
            ->header('订单')
            ->description('订单列表')
            ->body(function ($row) {
                $row->column(4, new Orders\DayOrderNumCount(['deduct'=>0]));
                $row->column(4, new Orders\DayOrderMoneyCount(['deduct'=>0]));
                $row->column(4, new Orders\DayOrderRaking);
            })
            ->body($this->grid());
    }
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Order(), function (Grid $grid) {
            $grid->model()->with('agent')->orderBy('created_at','desc');
            $grid->column('id')->sortable();
            $grid->column('video_id');
            $grid->column('订单信息')->display(function(){
                $price = "<span>金额：<span style='color:red;font-weight:bold'>￥$this->price</span></span></br>";
                $type= "<span>支付方式：$this->type</span></br>";
                $mchid = "<span>支付商户：$this->mch_id</span></br>";
                $no = "<span>订单号：$this->no</span></br>";
                $transaction_id = "<span>平台单号：$this->transaction_id</span></br>";
                $paid = "<span>支付时间：<span style='color:#1E90FF;font-weight:bold'>$this->paid_at</span></span>";
                return $price.$type.$mchid.$no.$transaction_id.$paid;
            });
            $grid->column('agent_price','代理金额')->sortable()->style('color:red;');
            $grid->column('agent_id')->filter();
            $grid->column('agent.username','代理名称');
            $grid->column('openid')->filter();
            // $grid->column('no');
            // $grid->column('type');
            // $grid->column('transaction_id','平台单号');
            // $grid->column('price')->sortable()->style('color:red;font-weight:bold;');
            // $grid->column('paid_at')->sortable()->display(function($paid_at){
            //     if(!boolval($paid_at)){
            //         return "<span style='color:gray;'>未支付</span>";
            //     }
            //     return "<span style='color:#1E90FF;font-weight:bold;'>$paid_at</span>";
            // });
            // $grid->column('appid')->filter();
            // $grid->column('mch_id')->filter();
            $grid->column('ip')->filter();
            $grid->column('created_at')->sortable()->filter();
            $grid->column('is_deduct')->sortable()->bool()->filter();
            $grid->column('valid')->sortable()->using([1 => '有效', 0 => '未支付'])->label([
                'default' => 'primary', // 设置默认颜色，不设置则默认为 default
                0 => 'danger',
                1 => 'success',
            ])->filter();
            $grid->created_at()->filter(
                Grid\Column\Filter\Between::make()->datetime()
            );
            $grid->actions([new ForbiddenOp()]);
            $grid->disableCreateButton();
            // $grid->disableActions();
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableView();
                $actions->disableEdit();
                $actions->disableDelete();
            });
            $grid->quickSearch(['no', 'video_id','agent_id','ip','transaction_id','openid','agent.username','mch_id']);
            $grid->filter(function (Grid\Filter $filter) {
                $filter->panel();
                $filter->expand();
                $filter->like('mch_id')->width(2);
                $filter->like('no')->width(2);
                $filter->like('transaction_id')->width(3);
                $filter->like('openid')->width(2);
                $filter->like('ip')->width(2);
                // 设置time类型
                $filter->between('paid_at')->datetime()->width(4);
            });

            $grid->header(function ($collection) use ($grid) {
                $query = \App\Models\Order::query();
                // 拿到表格筛选 where 条件数组进行遍历
                $grid->model()->getQueries()->unique()->each(function ($value) use (&$query) {
                    if (in_array($value['method'], ['paginate', 'get', 'orderBy', 'orderByDesc'], true)) {
                        return;
                    }
                    $query = call_user_func_array([$query, $value['method']], $value['arguments'] ?? []);
                });
                // 查出统计数据
                $data = $query->whereNotNull('paid_at')->sum('price');
                $data2 = $query->whereNotNull('paid_at')->sum('agent_price');
                return "<div style='padding-bottom: 10px;padding-left: 1.8rem;font-weight:bold;color:red;background:#fff;'>当前查询有效订单总金额 ：￥ $data - 【代理账面金额：￥ $data2 】</div> ";
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Order(), function (Show $show) {
            $show->field('id');
            $show->field('agent_id');
            $show->field('openid');
            $show->field('video_id');
            $show->field('no');
            $show->field('transaction_id');
            $show->field('price');
            $show->field('paid_at');
            $show->field('appid');
            $show->field('mch_id');
            $show->field('valid');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Order(), function (Form $form) {
            $form->display('id');
            $form->text('agent_id');
            $form->text('openid');
            $form->text('video_id');
            $form->text('no');
            $form->text('transaction_id');
            $form->text('price');
            $form->text('paid_at');
            $form->text('appid');
            $form->text('mch_id');
            $form->text('valid');
        
            $form->display('created_at');
            $form->display('updated_at');

            $form->deleted(function (Form $form, $result) {
                // 获取待删除行数据，这里获取的是一个二维数组
                $data = $form->model()->toArray();
                foreach($data as $item){
                    cache()->forget("paid:{$item['openid']}:{$item['video_id']}");
                    cache()->forget("paid_ip:{$item['ip']}:{$item['video_id']}");
                }
            });
        });
    }
}
